import { defineStore } from 'pinia'
import { getInfo, logoutUser, type UserInfo } from '@/api/login'
import { ListToTree } from '@/utils/tool'
import { checkPermission } from '@/utils/auth'
import { type Menu } from '@/api/power/menu'
import { type MenuOption } from 'naive-ui'
import { type RouteRecordRaw } from 'vue-router'
import router, { permissionRoutes } from '@/router'
import NotFind from '@/views/404.vue'

const useUserStore = defineStore(
  'user',
  () => {
    // 登录
    const token = ref('')
    // 用户信息
    const userInfo = ref<UserInfo>({
      username: '',
      token: '',
      roles: [],
      permissions: [],
      menus: []
    })
    // 侧边栏路由
    const sideBarRoutes = ref<MenuOption[]>([])
    // 注册路由
    const registerRoutes = ref<any[]>([])

    // 退出登录
    const logout = () => {
      logoutUser().then(() => {
        token.value = ''
        userInfo.value = <UserInfo>{}
        window.location.href = '/'
      })
    }
    // 获取用户信息
    const getUserInfo = () => {
      return getInfo().then(res => {
        userInfo.value = res.data
        generateRoutes()
        return registerRoutes.value
      })
    }

    // 生成路由
    const generateRoutes = () => {
      const menuList = userInfo.value.menus
      sideBarRoutes.value = formatSideBarRoutes(menuList)
      registerRoutes.value = formatRegisterRoutes(menuList)
      registerPermissionRoutes()
    }

    // 注册权限路由
    const registerPermissionRoutes = () => {
      permissionRoutes
        .filter(route => checkPermission(route.permission))
        .forEach(route => {
          router.addRoute('layout', route)
        })
    }

    // 格式化侧边栏路由
    const formatSideBarRoutes = (routes: Menu[]) => {
      const filterRoutes = routes
        .filter(row => row.menuType !== 2 && row.visible)
        .map(row => ({
          id: row.menuId,
          label: row.menuName,
          parentId: row.parentId,
          key: row.route,
          type: row.menuType === 0 ? 'group' : ''
        }))

      const treeRoutes = ListToTree(filterRoutes, 'id')

      return treeRoutes
    }
    // 格式化注册路由
    const formatRegisterRoutes = (routes: Menu[]): RouteRecordRaw[] => {
      const modules = import.meta.glob('./../views/**/*.vue')

      const list = routes
        .filter(row => row.menuType === 1)
        .map(row => {
          const routeItem = <RouteRecordRaw>{}
          const module = modules[`../views/${row.component}.vue`]
          routeItem.component = module

          routeItem.name = row.menuName
          routeItem.path = row.route as string
          routeItem.meta = {
            title: row.menuName,
            hidden: row.visible,
            route: row.route
          }
          return routeItem
        })
      list.push({
        path: '/:pathMatch(.*)*',
        name: 'not-find',
        component: NotFind
      })
      return list
    }

    return { token, userInfo, sideBarRoutes, logout, getUserInfo }
  },
  {
    persist: {
      paths: ['token']
    }
  }
)

export default useUserStore
